<?php
/**
 * Created by Administrator
 * User: longli
 * Date: 2020/08/12
 * Time: 10:52
 * @link http://www.lmterp.cn
 */

namespace app\common\service\platform;

use app\common\library\Tools;
use app\common\model\AccountSyncLog;
use app\common\model\Orders;
use app\common\model\OrdersTemp;
use app\common\service\orders\OrderService;
use Exception;
use Hitmeister\Component\Api\Client;
use Hitmeister\Component\Api\ClientBuilder;
use think\facade\Log;

/**
 * real 接口服务
 * Class RealService
 * @package app\common\service\real
 * @link https://www.real.de/api/v1/
 */
class RealService extends BasePlatformService
{
    public static $tokenField = [
        'required' => [ // 必填字段
            [
                'type' => 'text',
                'name' => 'key',
                'field' => 'key',
            ],
            [
                'type' => 'text',
                'name' => 'secret',
                'field' => 'secret',
            ],

        ],
        'option' => [ // 可选字段
        ],
    ];

    /**
     * 获取订单列表
     * @param array $params 参数配置，默认抓取当天订单
     * <ul>
     * <li>string start_date 开始抓取时间，默认为今天</li>
     * <li>string start_date 结束抓取时间，默认为当前时间</li>
     * <li>int page_size 分页大小，默认为 100 条</li>
     * </ul>
     * @param bool $replace 是否替换原有的订单，默认不替换
     * @return array|bool
     * @date 2020/08/13
     * @author longli
     * @link https://www.real.de/api/v1/order-units/seller/
     */
    public function getOrderList($params = [], $replace = false)
    {
        Log::info(sprintf("Real 批量同步账号【%d】订单，请求参数: 【%s】", $this->getAccountId(), json_encode($params)));
        $startSyncTime = time();
        $limit = !empty($params['page_size']) ? $params['page_size'] : 100;
        $from = !empty($params['start_date']) ? $params['start_date'] : strtotime("-1day");
        $to = !empty($params['end_date']) ? $params['end_date'] : null;
        $status = !empty($params['status']) ? $params['status'] : 'need_to_be_sent';
        $offset = 0;
        $client = $this->getClient();
        do
        {
            try
            {
                $orders = $client->orderUnits()->find($status, null, $from, $to, 'ts_created:desc', $limit, $offset * $limit);
                // $orders = $client->orderUnits()->find(null, null, null,null, 'ts_created:desc', $limit, $offset * $limit);
                // $orders = iterator_to_array($orders);
                foreach($orders as $order)
                {
                    $this->pushOrderToTemp($order->id_order, $order->toArray(), $replace);
                }
                $offset++;
                sleep(1); // 睡眠一秒
            }catch (Exception $e)
            {
                Log::info(sprintf("Real 批量同步账号【%d】订单，出现异常: 【%s】", $this->getAccountId(), $e->getMessage()));
                if(time() - $startSyncTime > 10) break;
                continue;
            }
        }while($orders->total() >= $limit * $offset);
        // 添加同步订单日志
        AccountSyncLog::addLog($this->getAccountId(), $startSyncTime, time(), $params);
    }

    public function markDelivery($orderIds = [])
    {
        foreach($this->getNeedMarkOrders($orderIds) as $order)
        {
            if($this->getClient()->orderUnits()->send($order->ext_json->id_order_unit, $order->logistics_name, $order->shipping_code))
            {
                $order->is_flag_sent = Orders::FLAG_SENT_YES;
                $order->sent_time = Tools::now();
                $order->save();
            }
            else
            {
                Log::info(sprintf("Real 订单号【%s】标记失败", $order->order_no));
            }
        }
    }

    /**
     * 获取头信息，自己计算
     * @param string $url url
     * @param string $body 请求体
     * @param string $method 请求方式
     * @date 2020/08/15
     * @author longli
     * @return string[]
     */
    public function getHeader($url, $body = '', $method = 'GET')
    {
        $method = strtoupper($method);
        $account = $this->getAccount();
        $string = join("\n", [$method, $url, $body, time()]);
            $sign = hash_hmac('sha256', $string, $account->token->secret);
        return [
            'Accept: application/json',
            'Hm-Client: ' . $account->token->key,
            'Hm-Timestamp: ' . time(),
            'Hm-Signature: ' . $sign,
        ];
    }

    /**
     * 获取官方请求客户端
     * @date 2020/08/15
     * @author longli
     * @return Client
     */
    public function getClient()
    {
        $account = $this->getAccount();
        return ClientBuilder::create()
            ->setClientKey($account->token->key)
            ->setClientSecret($account->token->secret)
            ->build();
    }

    /**
     * @inheritDoc
     */
    public function syncOrder(OrdersTemp $ordersTemp)
    {
        $data = $ordersTemp->order_info;
        $item = & $data['item'];
        $totalPrice = $data['price'] / 100;
        $shippingRate = $data['shipping_rate'] ? $data['shipping_rate'] / 100 : 0;
        $info = [];
        $info[] = [
            "item_id"       => $item['id_item'], // 商品 id
            "qty"           => 1, // 数量
            "return_qty"    => 0, // 取消数量
            "price"         => $totalPrice, // 售价
            "platform_sku"  => $data['id_offer'], // sku
            "image"         => $item['main_picture'], // 图片
            "name"          => $item['title'], // 产品名称
            'url'           => $item['url'], // 商品在线地址
        ];
        $platform = $this->getAccountById($ordersTemp->account_id)->platform;
        $address = & $data['shipping_address'];
        $order = [
            "order_no"                  => $ordersTemp->order_no,
            "account_id"                => $ordersTemp->account_id,
            "platform_name"             => $platform->name, // 平台名称
            "order_platform_status"     => $data['status'], // 订单在平台的状态
            "buyer_gender"              => $address['gender'], // 客户性别
            "buyer_company"             => $address['company_name'], // 客户公司
            "buyer_first_name"          => $address['first_name'], // 客户名称
            "buyer_last_name"           => $address['last_name'], // 客户名称
            "buyer_phone"               => $address["phone"], // 电话
            "buyer_country"             => '', // 国家
            "buyer_country_code"        => $address['country'], // 国家编码
            "buyer_district"            => $address['street'], // 区
            "buyer_city"                => $address['city'], // 城市
            "buyer_post_code"           => $address['postcode'], // 邮编
            "buyer_address_1"           => $address['house_number'], // 买家收货地址1
            "buyer_address_2"           => '', // 买家收货地址2
            "buyer_email"               => $data['buyer']['email'], // 买家邮箱
            "shipping_price"            => $shippingRate, // 订单运费
            "order_source_create_time"  => $this->parseTimeToDate($data['ts_created']), // 订单在平台生成的时间
            "latest_delivery_time"      => $this->parseTimeToDate($data['delivery_time_expires']), // 最迟发货时间
            "payment_method"            => null, // 支付方式
            "order_price"               => $totalPrice, // 订单金额
            "total_price"               => $totalPrice + $shippingRate, // 订单总金额
            "order_pay_time"            => null, // 订单支付时间
            "currency"                  => 'EUR', // 币种
            "invoice_category"          => $data['invoice'] ? $data['invoice']['type'] : '', // 发票种类
            "invoice_title"             => $data['invoice'] ? $data['invoice']['number'] : '', // 发票抬头
            "invoice_detail"            => $data['invoice'] ? $data['invoice']['url'] : '', // 发票详情
            "shipping_code"             => null, // 运单号
            "platform_remark"           => null, // 买家备注信息
            "ext_json"                  => ['id_order_unit' => $data['id_order_unit']],
            "order_detail" => $info,
        ];
        return OrderService::getInstance()->addOrder($order);
    }
}